'use strict';
const db = uniCloud.database();
const $ = db.command.aggregate;

/**
 * 获取班级统计信息
 * @param {Object} event - 请求参数
 * @param {string} event.className - 班级名称
 * @param {string} [event.teacher_id] - 教师ID
 * @returns {Object} - 返回班级统计数据
 */
exports.main = async (event, context) => {
  const { className, teacher_id } = event;
  
  console.log('getClassStats 输入:', { className, teacher_id });

  // 参数验证
  if (!className) {
    console.error('缺少 className');
    return { code: 400, msg: '缺少必要参数: className' };
  }
  if (!teacher_id) {
    console.error('缺少 teacher_id');
    return { code: 400, msg: '缺少必要参数: teacher_id' };
  }

  try {
    // 验证教师权限
    console.log('验证教师:', teacher_id);
    const teacherRes = await db.collection('users').where({ _id: teacher_id }).get();
    console.log('教师查询结果:', teacherRes);
    if (!teacherRes.data || teacherRes.data.length === 0 || teacherRes.data[0].role !== 'teacher') {
      console.error('权限错误: 非教师');
      return { code: 403, msg: '无权限访问班级数据' };
    }
    const teacher = teacherRes.data[0];
    if (!Array.isArray(teacher.className) || !teacher.className.includes(className)) {
      console.error('权限错误: 未管理班级', { teacherClassName: teacher.className, className });
      return { code: 403, msg: '您未管理该班级，请检查班级配置' };
    }

    // 聚合查询学生数据
    console.log('开始聚合查询，class_id:', className);
    const res = await db.collection('users')
      .aggregate()
      .match({
        role: 'student',
        class_id: className
      })
      .lookup({
        from: 'answer_history',
        localField: '_id',
        foreignField: 'user_id',
        as: 'answer_history'
      })
      .addFields({
        correct_count: $.size(
          $.filter({
            input: '$answer_history',
            as: 'item',
            cond: { $eq: ['$$item.correct', true] }
          })
        ),
        total_questions: $.size('$answer_history'),
        completed_lessons: 0, // 待确认
        total_lessons: 0, // 待确认
        last_checkin: {
          $ifNull: [
            {
              $dateToString: {
                format: '%Y-%m-%d',
                date: { $toDate: '$last_checkin' }
              }
            },
            ''
          ]
        }
      })
      .project({
        _id: 1,
        name: 1,
        student_id: 1,
        avatar: 1,
        points: 1,
        major: 1,
        consecutive_days: 1,
        correct_count: 1,
        total_questions: 1,
        completed_lessons: 1,
        total_lessons: 1,
        last_checkin: 1,
        class_id: 1
      })
      .sort({
        points: -1
      })
      .end();

    console.log('聚合查询结果:', res.data);
    return {
      code: 0,
      data: res.data,
      msg: '获取班级统计成功'
    };

  } catch (e) {
    console.error('getClassStats 失败:', e);
    return { 
      code: 500, 
      msg: '服务器错误',
      debug: e.message
    };
  }
};